<template>
  <div class="resource-management-container">
    <a-row :gutter="24">
      <a-col :span="6">
        <!-- 左侧资源目录 -->
        <a-card class="section-card resource-tree-card">
          <template #title>
            <div class="card-title-with-actions">
              <span>资源目录</span>
            </div>
          </template>
          <a-directory-tree
            v-model:selectedKeys="selectedKeys"
            :tree-data="buildResourceTree(dataList)"
            :expanded-keys="expandedKeys"
            @expand="onExpand"
          >
            <template #title="{ key, title }">
              <span>{{ title }}</span>
              <span class="tree-node-action" v-if="key !== 'root'">
                <more-outlined @click.stop="showNodeActions(key)" />
              </span>
            </template>
          </a-directory-tree>

          <!-- 文件夹统计 -->
          <div class="resource-stats">
            <div class="stat-item">
              <div class="stat-label">总资源数</div>
              <div class="stat-value">{{ statisticData?.totalResourceCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">文件夹数</div>
              <div class="stat-value">{{ statisticData?.totalCategoryCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">最大总容量</div>
              <div class="stat-value">{{ statisticData?.maxCapability }}</div>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="18">
        <!-- 右侧资源列表 -->
        <a-card class="section-card resource-list-card">
          <template #title>
            <div class="card-title-with-actions">
              <span>{{ currentFolder.title || '全部资源' }}</span>
              <div>
                <a-radio-group v-model:value="viewMode" button-style="solid" size="small">
                  <a-radio-button value="grid">
                    <appstore-outlined />
                  </a-radio-button>
                  <a-radio-button value="list">
                    <bars-outlined />
                  </a-radio-button>
                </a-radio-group>
                <a-button type="primary" style="margin-left: 16px" @click="showUploadModal">
                  <upload-outlined /> 上传资源
                </a-button>
              </div>
            </div>
          </template>

          <div class="resource-filter">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-select
                  placeholder="资源类型"
                  style="width: 100%"
                  @change="fetchData()"
                  v-model:value="searchParams.type"
                  allowClear
                >
                  <a-select-option :value="getFileSuffix('document')">文档</a-select-option>
                  <a-select-option :value="getFileSuffix('image')">图片</a-select-option>
                  <a-select-option :value="getFileSuffix('video')">视频</a-select-option>
                  <a-select-option :value="getFileSuffix('audio')">音频</a-select-option>
                  <a-select-option :value="getFileSuffix('other')">其他</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="8">
                <a-select
                  placeholder="上传时间"
                  style="width: 100%"
                  @change="fetchData()"
                  v-model:value="searchParams.intervalTime"
                  allowClear
                >
                  <a-select-option :value="1">今天</a-select-option>
                  <a-select-option :value="6">本周</a-select-option>
                  <a-select-option :value="30">本月</a-select-option>
                  <a-select-option :value="364">今年</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="8">
                <a-input-search
                  placeholder="搜索文件名"
                  v-model:value="searchParams.name"
                  @search="onResourceSearch"
                />
              </a-col>
            </a-row>
          </div>

          <!-- 网格视图 -->
          <div class="resource-grid" v-if="viewMode === 'grid'">
            <a-row :gutter="[16, 16]">
              <a-col :span="6" v-for="item in girdList" :key="item.id">
                <div class="resource-card" @click="selectResource(item)">
                  <div class="resource-icon">
                    <file-pdf-outlined v-if="item?.type === 'pdf'" />
                    <file-word-outlined v-else-if="item.type === 'doc'" />
                    <file-word-outlined v-else-if="item.type === 'docx'" />
                    <FileMarkdownOutlined v-else-if="item.type === 'md'"  />
                    <file-excel-outlined v-else-if="item.type === 'excel'" />
                    <file-ppt-outlined v-else-if="item.type === 'pptx'" />
                    <picture-outlined v-else-if="item.type === 'image'" />
                    <video-camera-outlined v-else-if="item.type === 'video'" />
                    <file-outlined v-else />
                  </div>
                  <div class="resource-info">
                    <div class="resource-name">{{ item.name }}</div>
                    <div class="resource-meta">
                      <span>{{ item.fileSize }}</span>
                      <span>{{ dayjs(item.publishTime).format('YYYY-MM-DD') }}</span>
                    </div>
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>

          <!-- 列表视图 -->
          <div class="resource-list" v-else>
            <a-table
              :columns="resourceColumns"
              :data-source="dataList"
              :pagination="pagination"
              :row-selection="{
                selectedRowKeys: selectedResourceKeys,
                onChange: onSelectChange,
              }"
              @change="handleTableChange"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'name'">
                  <div class="resource-name-cell">
                    <span class="resource-icon-small">
                      <file-pdf-outlined v-if="record.type === 'pdf'" />
                      <file-word-outlined v-else-if="record.type === 'doc'" />
                      <file-word-outlined v-else-if="record.type === 'docx'" />
                      <FileMarkdownOutlined v-else-if="record.type === 'md'"  />
                      <file-excel-outlined v-else-if="record.type === 'excel'" />
                      <file-ppt-outlined v-else-if="record.type === 'pptx'" />
                      <picture-outlined v-else-if="record.type === 'image'" />
                      <video-camera-outlined v-else-if="record.type === 'video'" />
                      <file-outlined v-else />
                    </span>
                    <span>{{ record.name }}</span>
                  </div>
                </template>
                <template v-else-if="column.dataIndex === 'publishTime'">
                  {{ dayjs(record.publishTime).format('YYYY-MM-DD') }}
                </template>
                <template v-if="column.key === 'action'">
                  <a-space>
                    <a @click="showResourceDetail(record)">查看</a>
                    <a-divider type="vertical" />
                    <a @click="downloadResource(record)">下载</a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      title="Are you sure delete this task?"
                      ok-text="Yes"
                      cancel-text="No"
                      @confirm="() => handleDelete(record)"
                      @cancel="cancel"
                    >
                      <a>删除</a>
                    </a-popconfirm>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 上传资源模态框 -->
    <a-modal v-model:open="uploadModalVisible" title="上传资源" @ok="handleUploadOk" width="600px">
      <a-form :model="uploadForm" layout="vertical">
        <a-form-item label="目标文件夹">
          <a-select
            v-model:value="categoryList"
            mode="tags"
            placeholder="请输入/选择文件夹"
            @change="handleChange"
          >
            <a-select-option v-for="(item, key) in statisticData?.categoryList" :value="item">{{
              item
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item name="name" label="名称">
          <a-input v-model:value="uploadForm.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item name="description" label="描述">
          <a-input v-model:value="uploadForm.description" placeholder="请输入描述" />
        </a-form-item>
        <a-form-item label="上传文件">
          <a-upload-dragger
            name="file"
            :multiple="false"
            :before-upload="beforeUpload"
            :custom-request="handleUpload"
            :show-upload-list="false"
          >
            <p class="ant-upload-drag-icon">
              <inbox-outlined />
            </p>
            <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p class="ant-upload-hint">支持单个或批量上传。文件大小不超过10MB。</p>
          </a-upload-dragger>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 预览资源模态框 -->
<!--    <a-modal
      v-model:open="previewModalVisible"
      :title="previewResource?.name || '资源预览'"
      @cancel="() => (previewModalVisible = false)"
      width="80%"
      style="top: 20px"
      :footer="null"
    >
      <div class="file-preview-container" v-if="previewResource">
        &lt;!&ndash; Word文档预览 &ndash;&gt;
        <template v-if="previewResource.type === 'docx'">
          <vue-office-docx
            :src="previewResource.fileUrl"
            :config="{ width: '100%', height: '70vh' }"
          />
        </template>
        &lt;!&ndash; PDF预览 &ndash;&gt;
        <template v-else-if="previewResource.type === 'pdf'">
          <vue-office-pdf
            :src="previewResource.fileUrl"
            :config="{ width: '100%', height: '70vh' }"
          />
        </template>
        &lt;!&ndash; Excel预览 &ndash;&gt;
        <template v-else-if="previewResource.type === 'xlsx'">
          <vue-office-excel
            :src="previewResource.fileUrl"
            :config="{ width: '100%', height: '70vh' }"
          />
        </template>
        &lt;!&ndash; 其他文件类型 &ndash;&gt;
        <template v-else>
          <div class="unsupported-file-type">
&lt;!&ndash;            <file-outlined style="font-size: 48px; color: #faad14" />
            <p>暂不支持该类型文件的预览，请下载后查看</p>
            <a-button type="primary" @click="() => downloadResource(previewResource)"
              >下载文件</a-button
            >&ndash;&gt;

          </div>
        </template>
      </div>
    </a-modal>-->
    <DocumentPreview ref="previewRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import {
  MoreOutlined,
  AppstoreOutlined,
  BarsOutlined,
  UploadOutlined,
  InboxOutlined,
  FilePdfOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FilePptOutlined,
  FileOutlined,
  PictureOutlined,
  VideoCameraOutlined,
  FileMarkdownOutlined
} from '@ant-design/icons-vue'
import { message, type UploadProps } from 'ant-design-vue'
import {
  addResource,
  deleteResource,
  getTotalResourceCount,
  listResourceVoByPage,
  uploadResourceFile,
} from '@/api/resourceController'
import dayjs from 'dayjs'
import { downloadFile } from '@/utils/file/download'
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeExcel from '@vue-office/excel'
import ToTop from '@/components/ToTop.vue'
import DocumentPreview from '@/components/common/preview/DocumentPreview.vue'
import type { PreviewOptions } from '@/components/common/preview/types'

// 资源列表列定义
const resourceColumns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 300,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    width: 400,
  },
  {
    title: '大小',
    dataIndex: 'fileSize',
    key: 'fileSize',
    width: 100,
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '上传时间',
    dataIndex: 'publishTime',
    key: 'publishTime',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]
//文件后缀相关
/* 后缀映射表 */
const EXTENSION_MAP: Record<string, string[]> = {
  document: ['doc', 'docx', 'pdf', 'txt', 'xls', 'xlsx', 'ppt', 'pptx'],
  image: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'],
  video: ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm'],
  audio: ['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'],
  other: ['zip', 'rar', '7z', 'exe', 'msi', 'apk'],
}
/* 响应式后缀列表 */
const getFileSuffix = (typeName: string) => {
  return EXTENSION_MAP[typeName] || []
}
//统计数据
const statisticData = ref<API.StatisticResourceVO>()
const fetchStatisticData = async () => {
  try {
    const res = await getTotalResourceCount()
    if (res.data.data && res.data.code === 0) {
      statisticData.value = res.data.data
    } else {
      message.error('获取个人资源数据失败')
    }
  } catch (e) {
    message.error('获取个人资源数据失败')
  }
}

//搜索条件 复用分页查询的接口
const searchParams = reactive<API.ResourceQueryRequest>({
  current: 1,
  pageSize: 10, //固定只能展示3个数据
})


//资源列表
const total = ref(0)
const dataList = ref<API.ResourceVO[]>([])
const fetchData = async () => {
  try {
    const res = await listResourceVoByPage({
      ...searchParams,
    })
    if (res.data.data && res.data.code === 0) {
      dataList.value = res.data.data.records || []
      total.value = Number(res.data.data.total)
    } else {
      message.error('获取资源列表失败')
    }
  } catch (e) {
    message.error('获取资源列表失败')
  }
}
const girdList = ref<API.ResourceVO[]>([])
const fetchGridData = async () => {
  try {
    const res = await listResourceVoByPage({
      current: 1,
      pageSize: 16, //固定展示16个数据
    })
    if (res.data.data && res.data.code === 0) {
      girdList.value = res.data.data.records || []
    } else {
      message.error('获取资源列表失败')
    }
  } catch (e) {
    message.error('获取资源列表失败')
  }
}
// 分页配置
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1, //有则按照传过来的，否则默认为1
    pageSize: searchParams.pageSize ?? 10, //默认为 10
    total: Number(total.value) ?? 0, //默认为 0
    showSizeChanger: true,
    showTotal: (total:Number) => `共${total}条数据`,
  }
})

// 处理表格变更（排序、筛选等）
const handleTableChange = (page: any, pageSize: any) => {
  //参数是改变后的页码及每页条数
  // 更新分页
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}
onMounted(() => {
  fetchStatisticData()
  fetchData()
  fetchGridData()
})

// 视图模式
const viewMode = ref('grid')

// 选中的目录节点
const selectedKeys = ref<string[]>(['root'])
const expandedKeys = ref<string[]>(['root'])
const currentFolder = ref({ key: 'root', title: '全部资源' })

// 选中的资源
const selectedResourceKeys = ref<string[]>([])
// 预览相关
const previewModalVisible = ref(false)
const previewResource = ref<API.ResourceVO>()

// 上传相关
const uploadModalVisible = ref(false)
const categoryList = ref<string[]>([])
const handleChange = (value: string) => {
  uploadForm.category = value[0]
}
const uploadForm = reactive<API.ResourceAddRequest>({
  id: '',
  category: '',
  name: '',
  description: '',
  fileList: [],
})
interface TreeNode {
  title: string
  key: string
  children?: TreeNode[]
}
const buildResourceTree = (list: API.ResourceVO[]) => {
  const root: TreeNode = {
    title: '全部资源',
    key: 'root',
    children: [],
  }

  // 按 category 分组
  const categoryMap: Record<string, API.ResourceVO[]> = {}
  list.forEach((item) => {
    const cat = item.category || '未分类'
    ;(categoryMap[cat] ||= []).push(item)
  })

  // 构造目录树
  Object.entries(categoryMap).forEach(([cat, files], idx) => {
    const folderNode: TreeNode = {
      title: cat,
      key: `folder${idx + 1}`,
      children: files.map((f, i) => ({
        title: f.name || '未命名文件',
        key: `folder${idx + 1}-${i + 1}`,
      })),
    }
    root.children!.push(folderNode)
  })

  return [root]
}
// 展开目录节点
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys
}

// 搜索资源
const onResourceSearch = (value: string) => {
  fetchData()
}

// 选择资源
const selectResource = (resource: API.ResourceVO) => {
  previewResource.value = resource
  previewModalVisible.value = true
  const ops: PreviewOptions = {
    watermark: 'EduAgentPro',
    saveable: true,
    title:resource.name,
  }
  previewRef.value?.open(previewResource.value.fileUrl,ops) // 运行时传参
}

// 表格选择变更
const onSelectChange = (selectedRowKeys: string[]) => {
  selectedResourceKeys.value = selectedRowKeys
}

// 显示资源详情
const previewRef = ref<{ open: (xurl?: string, ops?: PreviewOptions) => void; close: () => void } | null>(null)
const showResourceDetail = (resource: API.ResourceVO) => {
  previewResource.value = resource
  previewModalVisible.value = true
  const ops: PreviewOptions = {
    watermark: 'EduAgentPro',
    saveable: true,
    title:resource.name,
  }
  previewRef.value?.open(previewResource.value.fileUrl,ops) // 运行时传参
  // console.log("@@@@@@")
}

// 下载资源
const downloadResource = (resource: API.ResourceVO) => {
  downloadFile(resource?.fileUrl, resource?.name)
  message.success(`开始下载: ${resource.name}`)
}

// 处理删除
const handleDelete = async (record: any) => {
  try {
    const res = await deleteResource({
      id: record.id,
    })
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      message.success(`已删除资源 ${record.name}`)
    } else {
      message.error(`删除资源 ${record.name}失败`)
    }
  } catch (e) {
    message.error(`删除资源 ${record.name}失败`)
  }
}
const cancel = (e: MouseEvent) => {}

// 显示节点操作菜单
const showNodeActions = (key: string) => {
  console.log('显示操作菜单:', key)
}
//上传文件的响应对象
const currentFileInfo = ref<API.UploadReturnVO>()
// 显示上传模态框
const showUploadModal = () => {
  uploadModalVisible.value = true
}

// 处理上传确认 insert
const handleUploadOk = async () => {
  try {
    const res = await addResource({
      ...uploadForm,
      id: currentFileInfo.value?.id,
    })
    if (res.data.data && res.data.code === 0) {
      message.success('上传教学资源成功')
      await fetchData()
      await fetchStatisticData()
    } else {
      message.error('上传教学资源失败')
    }
  } catch (e) {
    message.error('上传教学资源失败')
  } finally {
    uploadModalVisible.value = false
  }
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB!')
  }

  return isLt10M
}

//处理上传
const handleUpload = async ({ file }: any) => {
  // 保存上传的文件信息

  const res = await uploadResourceFile(file)
  try {
    if (res.data.data && res.data.code === 0) {
      message.success('文件上传成功')
      currentFileInfo.value = res.data.data
    } else {
      message.error('文件上传失败,' + res.data.msg)
    }
  } catch (e) {
    message.error('文件上传失败,' + res.data.msg)
  }
}
</script>

<style scoped>
.resource-management-container {
  padding: 35px 20px;
  background: #f5f6fa;
  min-height: 90vh;
  height: 90.5vh;
  animation: fade-in-page 0.7s cubic-bezier(0.23, 1, 0.32, 1);
}

@keyframes fade-in-page {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: none;
  }
}

.page-title {
  font-size: 24px;
  margin-bottom: 24px;
  color: var(--primary-color);
}

.section-card {
  margin-bottom: 24px;
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: none;
  transition:
    box-shadow 0.3s,
    transform 0.3s;
  opacity: 0;
  animation: card-fade-in 0.7s cubic-bezier(0.23, 1, 0.32, 1) forwards;
}
.section-card:hover {
  box-shadow: 0 8px 32px rgba(24, 144, 255, 0.13);
  transform: translateY(-4px) scale(1.025);
}
@keyframes card-fade-in {
  to {
    opacity: 1;
    transform: none;
  }
}

.resource-tree-card {
  height: calc(100vh - 126px);
  overflow: auto;
}

.resource-list-card {
  min-height: calc(100vh - 160px);
}

.card-title-with-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  font-size: 18px;
  font-weight: 600;
  color: #222;
}

.tree-node-action {
  margin-left: 8px;
  visibility: hidden;
  transition: opacity 0.2s;
  opacity: 0;
}
:deep(.ant-tree-node-content-wrapper:hover) .tree-node-action {
  visibility: visible;
  opacity: 1;
}
:deep(.ant-tree .ant-tree-node-content-wrapper:hover) {
  background: #e6f7ff !important;
  color: #1890ff !important;
}

.resource-filter {
  margin-bottom: 24px;
}

.resource-stats {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: #888;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
}

.resource-card {
  padding: 16px;
  border: 1px solid var(--border-color);
  border-radius: 14px;
  transition:
    box-shadow 0.3s,
    transform 0.3s,
    background 0.3s;
  cursor: pointer;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  opacity: 0;
  animation: fade-in-card 0.7s cubic-bezier(0.23, 1, 0.32, 1) forwards;
}
.resource-card:hover {
  box-shadow: 0 8px 24px rgba(24, 144, 255, 0.13);
  transform: translateY(-4px) scale(1.04);
  background: #f0faff;
}
@keyframes fade-in-card {
  to {
    opacity: 1;
    transform: none;
  }
}

.resource-icon {
  font-size: 38px;
  text-align: center;
  margin-bottom: 12px;
  color: #1890ff;
  transition: transform 0.2s;
}
.resource-card:hover .resource-icon {
  transform: scale(1.12);
}

.resource-info {
  text-align: center;
}

.resource-name {
  font-size: 15px;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
  color: #222;
}

.resource-meta {
  font-size: 12px;
  color: #888;
  display: flex;
  justify-content: space-between;
}

.resource-name-cell {
  display: flex;
  align-items: center;
}

.resource-icon-small {
  margin-right: 8px;
  font-size: 16px;
  color: #1890ff;
  transition: transform 0.2s;
}
.resource-name-cell:hover .resource-icon-small {
  transform: scale(1.18);
}

:deep(.ant-btn-primary) {
  transition:
    background 0.2s,
    box-shadow 0.2s;
}
:deep(.ant-btn-primary:hover) {
  background: #40a9ff !important;
  box-shadow: 0 4px 16px rgba(24, 144, 255, 0.13);
}
:deep(.ant-radio-button-wrapper-checked) {
  background: #e6f7ff !important;
  color: #1890ff !important;
}

:deep(.ant-table) {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  animation: fade-in-table 0.7s cubic-bezier(0.23, 1, 0.32, 1);
}
@keyframes fade-in-table {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: none;
  }
}

/* 响应式优化 */
@media (max-width: 1200px) {
  .resource-tree-card,
  .resource-list-card {
    height: auto;
    min-height: 400px;
  }
  .resource-card {
    font-size: 14px;
  }
}
@media (max-width: 768px) {
  .resource-management-container {
    padding: 8px;
  }
  .section-card {
    border-radius: 10px;
    margin-bottom: 12px;
  }
  .resource-card {
    border-radius: 8px;
    padding: 10px;
  }
}
.file-preview-container {
  min-height: 400px;
  background: #f6faff;
  border-radius: 8px;
  padding: 24px 12px;
}
.unsupported-file-type {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  color: #faad14;
}
.unsupported-file-type p {
  margin: 16px 0 12px;
  color: #888;
}
</style>
